package com.ruoyi.product.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.product.domain.ProductComment;
import com.ruoyi.product.enums.CommentType;
import com.ruoyi.product.mapper.ProductCommentMapper;
import com.ruoyi.product.service.IMycommentService;
import com.ruoyi.product.service.QuanZiApi;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;


@Service
@Slf4j
public class QuanZiApiImpl implements QuanZiApi {
    @Autowired
    public ProductCommentMapper productCommentMapper;
    @Autowired
    public IMycommentService mycommentService;
    //评论数据存储在Redis中key的前缀
    private static final String COMMENT_REDIS_KEY_PREFIX = "QUANZI_COMMENT_";

    //⽤户是否点赞的前缀
    private static final String COMMENT_USER_LIEK_REDIS_KEY_PREFIX =
            "USER_LIKE_";

    //⽤户是否喜欢的前缀
    private static final String COMMENT_USER_LOVE_REDIS_KEY_PREFIX =
            "USER_LOVE_";
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public boolean saveLikeComment(Long userId, String publishId) {

        QueryWrapper<ProductComment> productCommentQueryWrapper = new QueryWrapper<>();
        productCommentQueryWrapper.eq("publish_id",publishId)
                .eq("user_id",userId)
                .eq("comment_type",CommentType.LIKE.toString());

        long count = this.productCommentMapper.selectCount(productCommentQueryWrapper);
        if (count > 0) {
            return false;
        }
        return this.saveComment(userId, publishId, String.valueOf(CommentType.LIKE.getType()), null);
    }
    @Override
    public Boolean queryUserIsLike(Long userId, String publishId) {
        //从redis中查询数据
        String redisKey = this.getCommentRedisKeyPrefix(publishId);
        String userHashKey = this.getCommentUserLikeRedisKeyPrefix(userId);
        Object data = this.redisTemplate.opsForHash().get(redisKey,
                userHashKey);
        if (ObjectUtil.isNotEmpty(data)) {
            return StrUtil.equals(Convert.toStr(data), "1");
        }
        QueryWrapper<ProductComment> productCommentQueryWrapper = new QueryWrapper<>();
        productCommentQueryWrapper.eq("user_id",userId)
                .eq("publish_id",publishId)
                .eq("comment_type",CommentType.LIKE.toString());
        Long number = productCommentMapper.selectCount(productCommentQueryWrapper);
        if(number == 0){
            return false;
        }
        //写⼊到redis中 绑定用户id 表示已经点赞过了
        this.redisTemplate.opsForHash().put(redisKey, userHashKey, "1");
        return true;
    }

    @Override
    public Long queryLikeCount(String publishId) {
        //从Redis中命中查询，如果命中直接返回即可
        String redisKey = this.getCommentRedisKeyPrefix(publishId);
        String hashKey = CommentType.LIKE.toString();
        Object data = this.redisTemplate.opsForHash().get(redisKey, hashKey);
        if (ObjectUtil.isNotEmpty(data)) {
            return Convert.toLong(data);
        }

        //查询
        Long count = this.queryCommentCount(publishId, CommentType.LIKE);
        //写⼊Redis中
        this.redisTemplate.opsForHash().put(redisKey, hashKey,
                String.valueOf(count));

        return count;
    }

    /**
     * 查询数量
     *
     * @param publishId
     * @param commentType
     * @return
     */
    private Long queryCommentCount(String publishId, CommentType commentType) {
        QueryWrapper<ProductComment> productCommentQueryWrapper = new QueryWrapper<>();
        productCommentQueryWrapper.eq("publish_id",publishId)
                        .eq("comment_type",commentType);
        Long result = productCommentMapper.selectCount(productCommentQueryWrapper);
        return result;
    }

    @Override
    public Long queryLoveCount(String publishId) {
        //⾸先从redis中命中，如果命中的话就返回，没有命中就查询Mongodb
        String redisKey = this.getCommentRedisKeyPrefix(publishId);
        String hashKey = CommentType.LOVE.toString();
        Object value = this.redisTemplate.opsForHash().get(redisKey, hashKey);
        if (ObjectUtil.isNotEmpty(value)) {
            return Convert.toLong(value);
        }

        //查询count
        Long count = this.queryCommentCount(publishId, CommentType.LOVE);

        //存储到redis中
        this.redisTemplate.opsForHash().put(redisKey, hashKey,
                String.valueOf(count));

        return count;
    }
    @Override
    public Boolean queryUserIsLove(Long userId, String publishId) {
        String redisKey = this.getCommentRedisKeyPrefix(publishId);
        String hashKey = this.getCommentUserLoveRedisKey(userId);
        Object value = this.redisTemplate.opsForHash().get(redisKey, hashKey);
        if (ObjectUtil.isNotEmpty(value)) {
            return StrUtil.equals(Convert.toStr(value), "1");
        }

        //查询
        QueryWrapper<ProductComment> productCommentQueryWrapper = new QueryWrapper<>();
        productCommentQueryWrapper.eq("publish_id",publishId)
                .eq("user_id",userId)
                .eq("comment_type",CommentType.LOVE.toString());
        Long count = productCommentMapper.selectCount(productCommentQueryWrapper);
        if (count == 0) {
            return false;
        }
        //标记⽤户已经喜欢
        this.redisTemplate.opsForHash().put(redisKey, hashKey, "1");

        return true;
    }

    @Override
    public String getCommentUserLoveRedisKey(Long userId) {
        return COMMENT_USER_LOVE_REDIS_KEY_PREFIX + userId;
    }



    @Override
    public String getCommentRedisKeyPrefix(String publishId) {
        return COMMENT_REDIS_KEY_PREFIX + publishId;
    }

    @Override
    public String getCommentUserLikeRedisKeyPrefix(Long userId) {
        return COMMENT_USER_LIEK_REDIS_KEY_PREFIX + userId;
    }
    @Override
    public boolean removeComment(Long userId, String publishId, Integer commentType) {
        QueryWrapper<ProductComment> productCommentQueryWrapper = new QueryWrapper<>();
        productCommentQueryWrapper.eq("user_id",userId)
                .eq("publish_id",publishId)
                .eq("comment_type",commentType.toString());
        int delete = productCommentMapper.delete(productCommentQueryWrapper);
        return true;
    }

    @Override
    public boolean saveLoveComment(Long userId, String publishId) {
        QueryWrapper<ProductComment> productCommentQueryWrapper = new QueryWrapper<>();
        productCommentQueryWrapper.eq("publish_id",publishId)
                .eq("user_id",userId)
                .eq("comment_type",CommentType.LOVE.toString());

        long count = this.productCommentMapper.selectCount(productCommentQueryWrapper);
        if (count > 0) {
            return false;
        }
        return this.saveComment(userId, publishId, String.valueOf(CommentType.LOVE.getType()), null);
    }

    /**
     * 保存Comment
     *
     * @return
     */

    @Override
    public Boolean saveComment(Long userId, String publishId,
                               String commentType, String content) {
        try {
            ProductComment comment = new ProductComment();
            comment.setUserId(userId);
            comment.setPublishId(Long.valueOf(publishId));
            // 评论类型
            comment.setCommentType(commentType);
            // 内容
            comment.setPublishContent(content);
            productCommentMapper.insert(comment);
            return true;
        } catch (Exception e) {
            log.error("保存Comment出错~ userId = " + userId + ", publishId = " +
                    publishId + ", commentType = " + commentType, e);
        }
        return false;
    }
}
